package com.teamb6.shop.config;

import com.teamb6.shop.util.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    private AdminDetailsService adminDetailsService;

    @Autowired
    public void setAnyUserDetailsService(AdminDetailsService adminDetailsService){
        this.adminDetailsService = adminDetailsService;
    }

    /**
     * 匹配 "/" 路径，不需要权限即可访问
     * 匹配 "/user" 及其以下所有路径，都需要 "ADMIN" 权限
     * 登录地址为 "/login"，登录成功默认跳转到页面 "/users/search"
     * 退出登录的地址为 "/logout"，退出成功后跳转到页面 "/login"
     * 默认启用 CSRF
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/adminlte/**","/bootstrap-table/**","/js/**","/css/**","/admin/login").permitAll()
                .antMatchers("/").authenticated()
                .antMatchers("/customers/**","/activity/**","/category/**","/goods/**","/indent/**").hasAuthority("ADMIN")
                .and()
                .formLogin().loginPage("/admin/login").loginProcessingUrl("/admin/confirmLogin").defaultSuccessUrl("/admin/success")
                .and()
                .logout().logoutUrl("/admin/logout").logoutSuccessUrl("/admin/login");
    }

    /**
     * 自定义登录校验
     */
    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception {
        builder.userDetailsService(adminDetailsService).passwordEncoder(new PasswordEncoder() {
            @Override
            public String encode(CharSequence rawPassword) {
                return Md5Util.MD5Encode((String) rawPassword,"utf-8");
            }

            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                return encodedPassword.equals(Md5Util.MD5Encode((String) rawPassword,"utf-8"));
            }
        });
    }

}
